$(function () {

    //正则验证
    var regTel = /^1[0-9]{10}$/;//验证手机号
    var regPass = /^[a-zA-Z0-9]{6,30}$/;//密码验证

    var headurl = localStorage.getItem("headurl");
	//登录的验证逻辑和ajax提交
	$(".login-form").validate({
		errorElement : 'span', 
        errorClass : 'help-block', 
        focusInvalid : false, 
        //自定义验证规则（表单控件的name）
		rules:{
			username:"required",
			userpassword:"required"
		},
		messages:{
			username:"用户账号不能为空",
			userpassword:"用户密码不能为空"
		},
		//给未通过验证的元素进行处理
		highlight : function(element) { 
                $(element).closest('.form-group').addClass('has-error'); 
        }, 
        //验证通过的处理
        success : function(label) { 
            label.closest('.form-group').removeClass('has-error'); 
            label.remove(); 
        }, 
        errorPlacement : function(error, element) { 
            element.parent('div').append(error); 
        },
        submitHandler : function(form) {
            //form.submit();
            //表单序列化根据表单控件的name属性实现，将表单元素值序列化成字符串
            var str = $(form).serialize();
            $.ajax({
				type:"post",
				url:"/api/v1/user/login?headurl="+headurl,
				data:str,
				dataType:"json",
				async:true,
				beforeSend:function(xhr){
					$("#divLoading").show();
					$("#msg").html("正在登陆中，请稍后...");
				},
				success:function(result,status,xhr){
					if(result.resCode==1){
						$("#msg").html("登陆成功，正在跳转中...");
						$("#divLoading").hide();
						localStorage.setItem("username",result.repBody.loginName);
                        localStorage.setItem("userId",result.repBody.id);
                        localStorage.setItem("personId",result.repBody.personId);
                        localStorage.setItem("mobile",result.repBody.mobile)
						window.location.href="/h5/index/home";//测试直接跳转
						//window.location.href="/h5/index/feeds";//跳转到控制层
					}
					else{
						$("#msg").html("登陆失败，用户名或密码有误");
					}
				},
				error:function(xhr,status,error){
					$("#msg").html("登陆失败，请检查网络");
				}
			});
        }
	});
	//键盘按下触发的验证
	$('.login-form input').keypress(function(e) {
        if (e.which == 13) {
            if ($('.login-form').validate().form()) {
                $('.login-form').submit(); //form validation success, call ajax form submit
            }
            return false;
        }
    });

    //注册
    $('#register-next-btn').on('click',function(){
        var mobile = $('#regusername1').val();
        var code = $("#verificationCode1").val();
        var pwd = $('#reguserpassword1').val();
        var pwd1 = $('#rpassword1').val();
        var loginName,cname,invitecode,iscoming,udid;
        if (mobile == "" || code == "" || pwd == "" || pwd1 == "") {
            $('#showerror p').text("请输入手机号,验证码和密码");
            $("#showerror").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }
        if (!regTel.test(mobile)) {
            $('#showerror p ').text("请输入十一位数的手机号码");
            $("#showerror").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }
        if (code == '' || typeof(code) == 'undefined') {
            $('#showerror p ').text("请输入正确的验证码");
            $("#showerror").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }
        if (!regPass.test(pwd)) {
            $('#showerror p ').text("密码支持6-20个字符长度");
            $("#showerror").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }
        if (pwd1 != pwd) {
            $('#showerror p ').text("两次输入密码不一致");
            $("#showerror").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }

        $('.login-form').hide();
        $('.register-form').hide();
        $('.forget-form').hide();
        $('.infomation-form').show();

        $('.btn-success').click(function () {
            var name1 = $('#regusername').val();
            var name2 = $('#reguserpassword2').val();
            var name = name1+name2;
            alert(name);
            if (name1 == "" || name2 == "") {
                $('#showerror1 p').text("请输入姓名");
                $("#showerror1").fadeIn(2000, function () {
                    $(this).fadeOut(2000);
                });
                return false;
            }

            getRegister(cname,mobile,pwd,code,invitecode,iscoming,udid);
            setTimeout(function () {
                window.location.href("/h5/user/login");
            }, 2000);
        });
        return false;
    });

    function getRegister(cname,mobile,pwd,code,invitecode,iscoming,udid) {
        var data = {
            "mobile": mobile,
            "pwd": pwd,
            "code": code,
        };
        $.ajax({
            type: "post",
            url: '/api/v1/user/register',//  register
            data: data,
            success: function (data) {
                if (data.resCode == 0) {
                    $('#showerror1 p ').text(data.resMsg);
                    $("#showerror1").fadeIn(1500, function () {
                        $(this).fadeOut(1500);
                    })
                } else {
                    $('#showerror1 p ').text('您已成功注册云谱账号！');
                    $("#showerror1").fadeIn(1500, function () {
                        $(this).fadeOut(1500, function () {
                            return false;
                        });
                    })
                }

            },
            error: function (msg) {
                console.log(msg)
            }
        });
    }

    //找回密码   忘记密码
    $('#passwardFind').click(function () {
        var code = $("#verificationCode").val(),
            mobile = $("#telFind").val(),
            pwd = $("#reguserpassword").val(),
            pwd1 = $("#rpassword").val();
        if (mobile == "" && pwd == "") {
            $('#showerror2 p ').text("请输入手机号和密码");
            $("#showerror2").fadeIn(1500, function () {
                $(this).fadeOut(1500);
            });
            return false;
        }
        if (!regTel.test(mobile)) {
            $('#showerror2 p ').text("联系电话支持11位数字输入");
            $("#showerror2").fadeIn(1500, function () {
                $(this).fadeOut(1500);
            })
            return false;
        }
        if (code == '' || typeof(code) == 'undefined') {
            $('#showerror2 p ').text("请输入正确的验证码");
            $("#showerror2").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }
        if (!regPass.test(pwd)) {
            $('#showerror2 p ').text("密码支持6-30个英文数字");
            $("#showerror2").fadeIn(1500, function () {
                $(this).fadeOut(1500);
            });
            return false
        }
        if (pwd1 !== pwd) {
            $('#showerror2 p ').text("两次输入密码不一致");
            $("#showerror2").fadeIn(2000, function () {
                $(this).fadeOut(2000);
            });
            return false;
        }
        get_forget(code, mobile, pwd);
    });
    function get_forget(code, mobile, pwd) {
        var data = {
            "code": code,
            "mobile": mobile,
            "pwd": pwd
        }
        $.ajax({
            type: "post",
            url: '/api/v1/user/recoverPwd ',//recoverPwd  findPassword
            data: data,
            success: function (data) {
                var resMsg = data.resMsg;
                if (data.resCode == 0) {
                    $('#showerror p ').text(resMsg);
                    $("#showerror").fadeIn(2000, function () {
                        $(this).fadeOut(2000);
                    })
                } else {
                    $('#showerror p ').text(resMsg);
                    $("#showerror").fadeIn(1500, function () {
                        $(this).fadeOut(1500, function () {
                            return false;
                        })
                    })
                }
            },
            error: function (msg) {
                console.log(msg)
            }
        });
    }

    //获取验证码
    $(function () {
        var flag = true;
        var onceGetTime = 60;
        $('#btn-vercode1').click(function () {
            var mobile = $('#regusername1').val();
            if (!regTel.test(mobile)) {
                $('#showerror p ').text("请输入11位数号码！");
                $("#showerror").fadeIn(2000, function () {
                    $(this).fadeOut(2000);
                });
                return false;
            } else{
                get_duanxin(mobile);
                return false;
            }
        });
        $('#btn-vercode').click(function () {
            var mobile = $('#telFind').val();
            if (!regTel.test(mobile)) {
                $('#showerror2 p ').text("请输入11位数号码！");
                $("#showerror2").fadeIn(2000, function () {
                    $(this).fadeOut(2000);
                });
                return false;
            } else{
                get_duanxin(mobile);
                return false;
            }
        });
        //短信验证码
        function get_duanxin(mobile) {
            $.ajax({
                type: "get",
                url: '/api/v1/user/sendMsg',
                data: {
                    "mobile": mobile
                },
                success: function (data) {
                    //console.log(data);
                    var resMsg = data.resMsg,
                        resMsgCode = data.code;
                    if (flag) {
                        getcode();
                    }
                    function getcode() {
                        sendCode();
                    }
                    function sendCode() {
                        if (onceGetTime > 1) {
                            onceGetTime--;
                            $('#btn-vercode1').text(onceGetTime + "s" + "后重新获取");
                            setTimeout(arguments.callee, 1000);
                            $('#btn-vercode1').css({
                                cursor: 'default',
                                border: '1px solid #ccc',
                                font: '15px/42px'
                            });
                            flag = false;
                        } else {
                            $('#btn-vercode1').html("再次获取验证码");
                            $('#btn-vercode1').css('cursor','pointer');
                            flag = true;
                            onceGetTime = 60;
                        }
                    }

                    $('#showerror p').text(resMsg);
                    $("#showerror").fadeIn(1000, function () {
                        $(this).fadeOut(1000);
                    });
                    return false;
                },
                error: function (msg) {
                    console.log(msg)
                }
            });
        }
    });

    jQuery('#register-btn').click(function() {
        jQuery('.login-form').hide();
        jQuery('.infomation-form').hide();
        jQuery('.register-form').show();
        jQuery('.forget-form').hide();
    });
    jQuery('#register-back-btn').click(function() {
        jQuery('.login-form').show();
        jQuery('.register-form').hide();
    });

    jQuery('#register-last-btn').click(function() {
        jQuery('.infomation-form').hide();
        jQuery('.register-form').show();
    });

    jQuery('#forget-password').click(function() {
        jQuery('.login-form').hide();
        jQuery('.forget-form').show();
    });

    jQuery('#forget-back-btn').click(function() {
        jQuery('.login-form').show();
        jQuery('.forget-form').hide();
    })
    
    //微信登录
    $(".wechatlogin").on("click",function () {
        var url="http://"+window.location.host+"/family-tree-web/api/v1/common/weixinLogin";
        window.location ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx812c260c8e3bf9aa&redirect_uri="+encodeURI(url)+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    })
});
